package com.xjc.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjc.business.entity.domain.*;
import com.xjc.business.entity.po.schadmin.SchAdminLoginPo;
import com.xjc.business.entity.po.schadmin.SchAdminRegisterPo;
import com.xjc.business.entity.vo.PageVo;
import com.xjc.business.entity.vo.schadmin.SchAdminLoginVo;
import com.xjc.business.entity.vo.sysadmin.PersonVo;
import com.xjc.business.entity.vo.sysadmin.SysAdminLoginVo;
import com.xjc.business.service.*;
import com.xjc.business.mapper.SchoolAdminsMapper;
import com.xjc.system.constants.MyConstants;
import com.xjc.system.exception.MyException;
import com.xjc.system.result.Result;
import com.xjc.system.result.ResultCode;
import com.xjc.system.utils.BcryptUtil;
import com.xjc.system.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author root
* @description 针对表【school_admins(学校管理员表)】的数据库操作Service实现
* @createDate 2025-01-25 10:24:32
*/
@Service
public class SchoolAdminsServiceImpl extends ServiceImpl<SchoolAdminsMapper, SchoolAdmins>
    implements SchoolAdminsService {

    @Autowired
    @Lazy
    SchoolAdminRelationsService schoolAdminRelationsService;

    @Autowired
    @Lazy
    SchoolsService schoolsService;

    @Autowired
    @Lazy
    SchoolApplysService schoolApplysService;

    @Autowired
    @Lazy
    SchoolSetsService schoolSetsService;

    /**
     * 注册
     *
     * @param schAdminRegisterPo 注册信息
     * @return 反馈
     */
    @Override
    public Result<String> doRegister(SchAdminRegisterPo schAdminRegisterPo) {
        LambdaQueryWrapper<SchoolAdmins> schoolAdminsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        schoolAdminsLambdaQueryWrapper.eq(SchoolAdmins::getUsername, schAdminRegisterPo.getUsername());

        if(count(schoolAdminsLambdaQueryWrapper) > 0){
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.USERNAME_EXIST);
        }

        SchoolAdmins schoolAdmins = new SchoolAdmins();
        schoolAdmins.setUsername(schAdminRegisterPo.getUsername());
        schoolAdmins.setPassword(BcryptUtil.hashPassword(schAdminRegisterPo.getPassword()));
        schoolAdmins.setNickname(schAdminRegisterPo.getNickname());
        schoolAdmins.setPhone(schAdminRegisterPo.getPhone());
        schoolAdmins.setEmail(schAdminRegisterPo.getEmail());
        schoolAdmins.setCreateTime(new Date());
        schoolAdmins.setUpdateTime(new Date());
        schoolAdmins.setStatus(1);

        save(schoolAdmins);

        return Result.okWithData("注册成功");
    }

    /**
     * 登录
     *
     * @param schAdminLoginPo 登录参数
     * @return 登录成功返回token，失败返回错误信息
     */
    @Override
    public Result<SchAdminLoginVo> doLogin(SchAdminLoginPo schAdminLoginPo) {

        String username = schAdminLoginPo.getUsername();
        String password = schAdminLoginPo.getPassword();

        LambdaQueryWrapper<SchoolAdmins> schoolAdminsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        schoolAdminsLambdaQueryWrapper.eq(SchoolAdmins::getUsername, username);

        SchoolAdmins schAdminsFromDB = getOne(schoolAdminsLambdaQueryWrapper);

        if (schAdminsFromDB == null){
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.USERNAME_ERROR);
        }

        if (!(BcryptUtil.checkPassword(password,schAdminsFromDB.getPassword()))){
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.PASSWORD_ERROR);
        }

        SchAdminLoginVo schAdminLoginVo = new SchAdminLoginVo();
        schAdminLoginVo.setId(schAdminsFromDB.getId());
        schAdminLoginVo.setUsername(schAdminsFromDB.getUsername());
        schAdminLoginVo.setNickname(schAdminsFromDB.getNickname());
        schAdminLoginVo.setPic(schAdminsFromDB.getPic());
        schAdminLoginVo.setToken(TokenUtils.generateToken(schAdminsFromDB.getId()));

        // 查询所管理的学校
        LambdaQueryWrapper<SchoolAdminRelations> schoolAdminRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        schoolAdminRelationsLambdaQueryWrapper.eq(SchoolAdminRelations::getSchAdminId, schAdminsFromDB.getId());

        SchoolAdminRelations schoolAdminRelationsFromDB = schoolAdminRelationsService.getOne(schoolAdminRelationsLambdaQueryWrapper);

        if(schoolAdminRelationsFromDB!=null){
            schAdminLoginVo.setSchoolId(schoolAdminRelationsFromDB.getSchId());

            // 查询是否开通套餐
            LambdaQueryWrapper<SchoolSets> schoolSetsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            schoolSetsLambdaQueryWrapper.eq(SchoolSets::getSchId, schoolAdminRelationsFromDB.getSchId());
            SchoolSets schoolSets = schoolSetsService.getOne(schoolSetsLambdaQueryWrapper);
            if(schoolSets != null && schoolSets.getPayStatus().equals(MyConstants.SET_HAS_PAY) && schoolSets.getSetEndTime().after(new Date())){
                schAdminLoginVo.setHasActive(true);
            }else{
                LambdaQueryWrapper<SchoolSets> schoolSetsLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                schoolSetsLambdaQueryWrapper2.eq(SchoolSets::getSchId, schoolAdminRelationsFromDB.getSchId());
                schoolSetsService.remove(schoolSetsLambdaQueryWrapper2);
                schAdminLoginVo.setHasActive(false);
            }
        }else{
            schAdminLoginVo.setHasActive(false);
        }


        return Result.okWithData(schAdminLoginVo);
    }

    /**
     * 分页查询学校管理员
     *
     * @param pageSize    每页条数
     * @param currentPage 当前页码
     * @param username    用户名
     * @param nickname    昵称
     * @param status      状态
     * @return 数据
     */
    @Override
    public Result<PageVo<PersonVo>> getPersonPage(Integer pageSize, Integer currentPage, String username, String nickname, Integer status) {

        LambdaQueryWrapper<SchoolAdmins> schoolAdminsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        schoolAdminsLambdaQueryWrapper.like(!username.isEmpty(),SchoolAdmins::getUsername,username);
        schoolAdminsLambdaQueryWrapper.like(!nickname.isEmpty(),SchoolAdmins::getNickname,nickname);
        schoolAdminsLambdaQueryWrapper.eq(!status.equals(-1),SchoolAdmins::getStatus,status);

        Page<SchoolAdmins> schoolAdminsPage = new Page<>(currentPage, pageSize);
        page(schoolAdminsPage, schoolAdminsLambdaQueryWrapper);
        List<SchoolAdmins> schoolAdminsPageRecords = schoolAdminsPage.getRecords();
        List<PersonVo> personVoList = schoolAdminsPageRecords.stream().map(schoolAdmins -> {
            PersonVo personVo = new PersonVo();
            personVo.setId(schoolAdmins.getId());
            personVo.setUsername(schoolAdmins.getUsername());
            personVo.setNickname(schoolAdmins.getNickname());
            personVo.setPic(schoolAdmins.getPic());
            personVo.setPhone(schoolAdmins.getPhone());
            personVo.setEmail(schoolAdmins.getEmail());
            personVo.setStatus(MyConstants.USER_STATUS.get(schoolAdmins.getStatus()));
            personVo.setCreateTime(schoolAdmins.getCreateTime());
            personVo.setUpdateTime(schoolAdmins.getUpdateTime());

            LambdaQueryWrapper<SchoolAdminRelations> schoolAdminRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            schoolAdminRelationsLambdaQueryWrapper.eq(SchoolAdminRelations::getSchAdminId,schoolAdmins.getId());

            SchoolAdminRelations schoolAdminRelationsFromDB = schoolAdminRelationsService.getOne(schoolAdminRelationsLambdaQueryWrapper);

            if(schoolAdminRelationsFromDB!=null){
                Integer schId = schoolAdminRelationsFromDB.getSchId();
                String schoolName = schoolsService.getById(schId).getSchoolName();
                personVo.setRelationSchoolName(schoolName);
            }

            return personVo;
        }).collect(Collectors.toList());

        PageVo<PersonVo> pageVo = new PageVo<>();
        pageVo.setData(personVoList);
        pageVo.setTotal(schoolAdminsPage.getTotal());
        pageVo.setCurrent(currentPage);
        pageVo.setSize(pageSize);
        pageVo.setPageCount(schoolAdminsPage.getPages());

        return Result.okWithData(pageVo);
    }
}




